package com.hjs.test.util;

import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class TokenUtils {
    static String token;
    static AtomicInteger token_seq = new AtomicInteger(0);
    public static String getToken(){
        if(Objects.isNull(token)){
            synchronized (TokenUtils.class){
                if(Objects.isNull(token)){
                    generateToken();
                }
            }
        }
        return token;
    }

    private static void generateToken(){
        token = String.format("the-token-%d", token_seq.getAndIncrement());
    }

    public static void main(String[] args) {
        int threadCount = 1_000;
        CountDownLatch latch = new CountDownLatch(threadCount);
        for(int i=0;i<threadCount;i++){
            new Thread(() ->{
                latch.countDown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(getToken());
            }).start();
        }
    }
}
